package adavance.socket;

 
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class AdvanceChatServer {
    public static void main(String[] args) {
        try {
            ServerSocket st=new ServerSocket(9998);
            System.out.println("服务器启动成功，监听在9998端口");
            while (true){
                final Socket s = st.accept();
                //////new ChatThread(s).start();
                new FileThread(s).start();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

class ChatThread extends Thread{
    private final Socket s;

    public ChatThread(Socket s){
        this.s=s;
    }
    @Override
    public void run() {
        System.out.println(s+"连上了。。。");
        //io通道建立
        try {
            System.out.println("连接信息："+s.getPort()+","+s.getInetAddress());
            InputStream in = s.getInputStream();
            OutputStream out = s.getOutputStream();
            //处理行，因为行 \n 结束标记
            BufferedReader br=new BufferedReader(new InputStreamReader(in));
            PrintWriter pw=new PrintWriter(out,true);//flush不用了，因为他自动刷新
            String ask=null,reply=null;
            while (true){
                //你问我答的方式
                ask=br.readLine();
                if(ask==null||ask.length()==0)
                    break;
                System.out.println(s+"问"+ask);
                reply="你问的话"+ask+"]朕知道了，等我给你下旨回复";
                pw.println(reply);
                //pw.flush();
                if(ask.equals("exit"))
                    break;

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                System.out.println(s+"退出了，关闭");
                s.close();
            } catch (Exception e) {

            }
        }
    }
}

class FileThread extends Thread{
    private final Socket s;
    public FileThread(Socket s){
        this.s=s;
    }
    public static final String FILENAME="d://2.jpg";
    @Override
    public void run() {
        try {
            //从文件中读，通过out流，发送到客户端
            //从流中读取内容，写到文件中去
            System.out.println("准备发文件给："+s);
            OutputStream out = s.getOutputStream();
            FileInputStream fin=new FileInputStream(FILENAME);
            byte b[]=new byte[fin.available()];//有隐患，大文件有问题
            int len = fin.read(b);
            //读到的文件内容，发给客户端
            out.write(b,0,len);
            out.flush();
            System.out.println("文件发送给"+s+"结束");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                s.close();
            } catch (Exception e) {

            }
        }

    }
}